﻿#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
private:
    const static int inf = 0x3f3f3f3f;
    int maxans = -inf;
    int dfs(TreeNode* r) {
        if (r == nullptr) return 0;
        int g0 = dfs(r->left);
        int g1 = dfs(r->right);
        int single_side = max(0, max(g0, g1)) + r->val;
        int both_side = g0 + g1 + r->val;
        int c_max_route = max(single_side, both_side);
        maxans = max(maxans, c_max_route);
        return single_side;
    }
public:
    int maxPathSum(TreeNode* root) {
        dfs(root);
        return maxans;
    }
};

Solution solution;

int main() {
    TreeNode* tree = new TreeNode(-10, new TreeNode(9), new TreeNode(20, new TreeNode(15), new TreeNode(7)));
    cout << solution.maxPathSum(tree) << endl;
    return 0;
}